package casa.depesos.app.com.frag;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.SPHelper;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.App;
import casa.depesos.app.com.R;
import casa.depesos.app.com.activity.BankActivity;
import casa.depesos.app.com.activity.CardActivity;
import casa.depesos.app.com.activity.CardSureActivity;
import casa.depesos.app.com.activity.Check2Activity;
import casa.depesos.app.com.activity.CheckActivity;
import casa.depesos.app.com.activity.FaceActivity;
import casa.depesos.app.com.activity.InfoActivity;
import casa.depesos.app.com.activity.MainActivity;
import casa.depesos.app.com.activity.TouchActivity;
import casa.depesos.app.com.activity.WorkActivity;
import casa.depesos.app.com.databinding.FragmentHomeBinding;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.BankCardBean;
import casa.depesos.app.com.http.bean.CardInfoBean;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.bean.HomeConfigBean;
import casa.depesos.app.com.http.bean.LevelBean;
import casa.depesos.app.com.http.data.HomeConfig;
import casa.depesos.app.com.http.req.BankCardReq;
import casa.depesos.app.com.http.req.CardInfoReq;
import casa.depesos.app.com.http.req.HomeConfigReq;
import casa.depesos.app.com.http.req.IsFirstReq;
import casa.depesos.app.com.http.req.LevelReq;
import casa.depesos.app.com.http.req.ReApplyReq;
import casa.depesos.app.com.http.req.no.DailyRateReq;
import casa.depesos.app.com.http.req.no.FeeReq;
import casa.depesos.app.com.it.Refreshable;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class HomeFragment extends BannerBaseFragment implements Refreshable {

    FragmentHomeBinding binding;
    int status;
    final ArrayList<String> amount = new ArrayList<>();

    public HomeFragment setStatus(int status) {
        this.status = status;
        return this;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Report.show("ACTION_HH_001");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Report.exit("ACTION_UU_001");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        binding.rela.setPadding(0, Utils.getStatusBarHeight(getActivity()), 0, 0);
        if (status >= 20 && status < 100) {
            binding.tip.setVisibility(View.VISIBLE);
        } else {
            binding.tip.setVisibility(View.INVISIBLE);
        }
        binding.take.setOnClickListener(v -> {
            Report.click("ACTION_HH_002");
            switch (status) {
                case 0:
                    ((MainActivity) getActivity()).getData();
                    break;
                case 10: {
                    getLevel(new Runnable() {
                        @Override
                        public void run() {
                            Intent i = new Intent(getActivity(), InfoActivity.class);
                            i.putStringArrayListExtra("amount", amount);
                            startActivity(i);
                        }
                    });
                    break;
                }
                case 20: {
                    getLevel(new Runnable() {
                        @Override
                        public void run() {
                            Intent i = new Intent(getActivity(), WorkActivity.class);
                            i.putStringArrayListExtra("amount", amount);
                            startActivity(i);
                        }
                    });
                    break;
                }
                case 25: {
                    getLevel(new Runnable() {
                        @Override
                        public void run() {
                            Intent i = new Intent(getActivity(), TouchActivity.class);
                            i.putStringArrayListExtra("amount", amount);
                            startActivity(i);
                        }
                    });
                    break;
                }
                case 30: {
                    toCard();
                    break;
                }
                case 40: {
                    Intent i = new Intent(getActivity(), FaceActivity.class);
                    startActivity(i);
                    break;
                }
                case 50: {
                    showLoading();
                    new BankCardReq().req(new ReqCallback<BankCardBean>() {
                        @Override
                        public void callback(boolean success, BankCardBean bean) {
                            hideLoading();
                            if (bean != null) {
                                if (bean.isValid()) {
                                    Intent i = new Intent(getActivity(), CheckActivity.class);
                                    startActivity(i);
                                } else {
                                    Intent i = new Intent(getActivity(), BankActivity.class);
                                    i.putExtra("from", 2);
                                    startActivity(i);
                                }
                            }
                        }
                    });
                    break;
                }
                case 62:
                case 92: {
                    Report.toMone();
                    showLoading();
                    new ReApplyReq().req(new ReqCallback<GetCodeBean>() {
                        @Override
                        public void callback(boolean success, GetCodeBean bean) {
                            hideLoading();
                            if (success) {
                                Intent i = new Intent(getActivity(), Check2Activity.class);
                                startActivity(i);
                            }
                        }
                    });
                    break;
                }
                case 600: {
                    check();
                    break;
                }
            }
        });

        return binding.getRoot();
    }

    private void check() {
        XXPermissions.with(this).permission(Permission.ACCESS_COARSE_LOCATION, Permission.READ_PHONE_STATE, Permission.READ_SMS, Permission.RECEIVE_SMS).request(new OnPermissionCallback() {
            boolean deal = false;

            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                next(allGranted, false);
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                next(false, doNotAskAgain);
            }

            void next(boolean granted, boolean doNotAskAgain) {
                if (deal) {
                    return;
                }
                deal = true;
                if (granted) {
                    Report.toMone();
                    showLoading();
                    new ReApplyReq().req(new ReqCallback<GetCodeBean>() {
                        @Override
                        public void callback(boolean success, GetCodeBean bean) {
                            hideLoading();
                            if (success) {
                                Intent i = new Intent(getActivity(), Check2Activity.class);
                                startActivity(i);
                            }
                        }
                    });
                } else {
                    ToastUtil.showLongToast(getActivity(), "Asegúrese de que los permisos de SMS, ubicación y dispositivo estén habilitados, de lo contrario, puede habilitarlos en Configuración");
                }
            }
        });
    }

    private void toCard() {
        if (true) {
            Intent i = new Intent(getActivity(), CardActivity.class);
            startActivity(i);
            return;
        }
        showLoading();
        new CardInfoReq(false).req(new ReqCallback<CardInfoBean>() {
            @Override
            public void callback(boolean success, CardInfoBean bean) {
                hideLoading();
                if (success && bean.isValid() && !Constant.white) {
                    Intent i = new Intent(getActivity(), CardSureActivity.class);
                    i.putExtra("card", bean.card);
                    startActivity(i);
                } else {
                    Intent i = new Intent(getActivity(), CardActivity.class);
                    startActivity(i);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        update();
    }

    private void update() {
        getName(binding.top);
        getUnRead(binding.top);
        getLink(binding.bottom);
        getConfig();
        showMsg(binding.msg, binding.scroll);
        getLevel(null);
        getBanner(binding.banner);

        new IsFirstReq().req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                boolean first = bean != null && "true".equalsIgnoreCase(bean.toString());
                if (first) {
                    new DailyRateReq().req();
                    new FeeReq().req();
                }
            }
        });
    }

    private void getConfig() {
        new HomeConfigReq().req(new ReqCallback<HomeConfigBean>() {
            @Override
            public void callback(boolean success, HomeConfigBean bean) {
                if (Constant.white) {
                    bean = new HomeConfigBean();
                    bean.config = new HomeConfig();
                    bean.config.amount = "10000";
                    bean.config.days = "180,270";
                }
                if (bean != null && bean.isValid()) {
                    bean.config.days = "120,240,365";
                    binding.s.setVisibility(View.VISIBLE);
                    SPHelper.getInstance(App.getApp()).putString("max", bean.config.amount).commit();
                    binding.max.setText(Utils.formatNoFloat(bean.config.amount));
                    binding.days.removeAllViews();
                    if (!TextUtils.isEmpty(bean.config.days)) {
                        String[] tmp = bean.config.days.split(",");
                        int ten = Utils.dp2Px(App.getApp(), 10);
                        for (String s : tmp) {
                            TextView tv = new TextView(getActivity());
                            tv.setText(s + "días");
                            tv.setBackgroundResource(R.drawable.day_bg);
                            tv.setGravity(Gravity.CENTER);
                            tv.setTextColor(0xff23774D);
                            tv.setTextSize(12);
                            tv.setPadding(ten, 0, ten, 0);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                            params.leftMargin = ten / 2;
                            binding.days.addView(tv, params);
                        }
                    }
                }
            }
        });
    }

    private void getLevel(Runnable runnable) {
        if (!amount.isEmpty()) {
            runnable.run();
            return;
        }
        new LevelReq().req(new ReqCallback<LevelBean>() {
            @Override
            public void callback(boolean success, LevelBean bean) {
                if (Constant.white && runnable != null) {
                    runnable.run();
                    return;
                }
                if (success && bean.isValid()) {
                    amount.clear();
                    amount.addAll(bean.list);
                    if (runnable != null) {
                        runnable.run();
                    }
                }
            }
        });
    }

    @Override
    public void refresh() {
        update();
    }
}
